<template>
	<section>
		<!--工具条-->
		<!--列表-->
		<el-table :data="users" stripe highlight-current-row v-loading="listLoading" border @selection-change="selsChange" style="width: 100%;">
			<el-table-column prop="id" label="ID" min-width="30" align="center"></el-table-column>
			<el-table-column prop="vipName" label="会员名称" min-width="80" align="center"></el-table-column>
            <el-table-column prop="byPrice" label="会员价格" min-width="80" align="center"></el-table-column>
            <el-table-column prop="extendCount" label="升级该等级需要推广的人数" min-width="80" align="center"></el-table-column>
            <el-table-column prop="goodsOneLevelExtendScale" label="商品默认一级推广比例" min-width="80" align="center"></el-table-column>
            <el-table-column prop="goodsTwoLevelExtendScale" label="商品默认二级推广比例" min-width="80" align="center"/>
            <el-table-column prop="oneLevelExtendAmount" label="一级推广金额" min-width="80" align="center"></el-table-column>
            <el-table-column prop="twoLevelExtendAmount" label="二级推广金额" min-width="80" align="center"></el-table-column>
            <el-table-column prop="sales" label="销量" min-width="80" align="center"></el-table-column>
			<el-table-column label="操作" min-width="60" align="center">
				<template slot-scope="scope">
					<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--编辑界面-->
		<el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false" width="800px">
			<el-form :model="editForm" label-width="180px" ref="editForm">
				<el-form-item label="优惠券" prop="couponId">
		            <el-select v-model="editForm.couponId" clearable> 
		                <el-option v-for="item in couponList" :key="item.id" :label="item.couponsName" :value="item.id" ></el-option>
		            </el-select>
				</el-form-item>
				<el-form-item label="会员名称" prop="vipName">
					<el-input  v-model="editForm.vipName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="会员价格" prop="byPrice">
					<el-input  v-model="editForm.byPrice" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="升级该等级需要推广的人数" prop="extendCount" v-if="editForm.vipType != 1">
					<el-input  v-model="editForm.extendCount" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="商品默认一级推广比例" prop="goodsOneLevelExtendScale">
					<el-input  v-model="editForm.goodsOneLevelExtendScale" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="商品默认二级推广比例" prop="goodsTwoLevelExtendScale" v-if="editForm.vipType != 1">
					<el-input  v-model="editForm.goodsTwoLevelExtendScale" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="一级推广金额" prop="oneLevelExtendAmount">
					<el-input  v-model="editForm.oneLevelExtendAmount" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="二级推广金额" prop="twoLevelExtendAmount">
					<el-input  v-model="editForm.twoLevelExtendAmount" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="会员销量" prop="sales">
					<el-input  v-model="editForm.sales" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="商品详情" prop="detail">
                    <quill-editor id="editor" v-model="editForm.goodsInfo.detail" ref="myQuillEditor" :options="editorOption" @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @change="onEditorChange($event)"></quill-editor>
                    <el-upload class="avatar-uploader" :http-request="uploadImage" :multiple="true" :show-file-list="false" action="" :before-upload="beforeAvatarUpload" accept="image/*"></el-upload>
                </el-form-item>
				<el-form-item label="商品图片">
					<div class="uploadImg">
						<div v-for="(tab,index) in this.urlList" class="uploadImgItem" :key="index">
							<img :src="tab" style="width: 145px;height: 145px;border-radius: 5px;object-fit: cover;">
						    <img class="uploadImgItemDel" @click="handleAddDel(index)" src="http://blyw.oss-cn-hangzhou.aliyuncs.com/webStorage/web_1619754060794173.png"/>
						</div>
						<el-upload class="avatar-uploader photo" list-type="picture-card" :http-request="(res)=>{return Upload(res)}" :multiple="true" :show-file-list="false" action="" :before-upload="beforeAvatarUpload" accept="image/jpeg,image/png">
							<i class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</div>
				</el-form-item>
				<el-form-item label="商品订单图片" prop="picUrl">
					<el-upload class="avatar-uploader photo" list-type="picture-card" :http-request="(res)=>{return Upload1(res, 'picUrl')}" :multiple="false" :show-file-list="false" action="" :before-upload="beforeAvatarUpload" accept="image/jpeg,image/png">
						<img v-if="editForm.goodsInfo.picUrl" :src="editForm.goodsInfo.picUrl" class="avatar" width="145" height="145">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click.native="editFormVisible = false">取消</el-button>
				<el-button size="mini" type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import { client ,getFileNameUUID} from '../../common/js/alioss'
	import util from '../../common/js/util'
		const toolbarOptions = [
		[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
		['bold', 'italic', 'underline', 'strike'],// toggled buttons
		['blockquote', 'code-block'],
		[{ 'list': 'ordered'}, { 'list': 'bullet' }],
		[{ 'indent': '-1'}, { 'indent': '+1' }], // outdent/indent
		[{ 'direction': 'rtl' }], // text direction
		[{ 'align': [] }],
		['image']
	]
	export default {
		data() {
			return {
				filters:{
					name:'',
				},
				sels:[],
				couponList:[],
				users: [],
				total: 0,
				page: 1,
				pageSize: 10,
				listLoading: false,
				editFormVisible: false,
				editLoading: false,
				editForm: {
					id: '',
					vipName:'',
					byPrice: '',
					extendCount:'',
					goodsOneLevelExtendScale:'',
					goodsTwoLevelExtendScale:'',
					oneLevelExtendAmount:'',
					twoLevelExtendAmount:'',
					vipType:'',
					couponId:'',
					sales:'',
					goodsInfo:{
						name:'',
						brief:'',
						detail:'',
						picUrl:''
					}
				},
				urlList:[],
				editorOption: {
			        placeholder: '',
			        theme: 'snow',  // or 'bubble'
			        modules: {
			            toolbar: {
			                container: toolbarOptions,  // 工具栏
			                handlers: {
			                    'image': function (value) {
			                        if (value) {
			                        // 触发input框选择图片文件
			                            document.querySelector('.avatar-uploader input').click()
			                        } else {
			                            this.quill.format('image', false);
			                        }
			                    }
			                }
			            }
			        }
			    },
			}
		},
		methods: {
			//添加图片
		    beforeAvatarUpload(file) {},//图片上传到阿里云
		    Upload1(file, index) {
				var fileName = 'webStorage/web_' + file.file.uid+Math.floor(Math.random()*10000) + file.file.name.substr(file.file.name.indexOf("."));
				client().put(fileName, file.file).then(result => {
					this.editForm.goodsInfo.picUrl = result.url;
					console.log(this.addForm[index]);
				}).catch(function (err) {
                    console.log(err);
	 			});
            },
			//新增商品主图片
			Upload(file) {
				var fileName = 'webStorage/web_' + file.file.uid+Math.floor(Math.random()*10000) + file.file.name.substr(file.file.name.indexOf("."));
				client().put(fileName, file.file).then(result => {
					console.log(result.url.substring(58))
					let dataUrl = result.url
					this.urlList.push(dataUrl)
				}).catch(function (err) {
                    console.log(err);
	 			});
			},
			//删除新增主体图片
			handleAddDel(index){
				this.urlList.splice(index,1)
				console.log(this.urlList,'this.urlList')
			},
			//失去焦点事件
		    onEditorBlur(editor){
		    },
		    //获得焦点事件
		    onEditorFocus({editor,html,text}){
			    let dada = editor.delta.ops
			    let imgValue = dada.filter(item => {
			        if (item.insert.image) {
			            return true
			        }
			    }).map(item => item.insert.image).toString()
			    this.images = imgValue
		    },
		    //编辑器文本发生变化
		    onEditorChange({editor,html,text}){
		//      this.editForm.photo=[]
		    },
		    uploadImage(file) {
		        var fileName = 'webStorage/web_' + file.file.uid+Math.floor(Math.random()*10000) + file.file.name.substr(file.file.name.indexOf("."));
		        let quill = this.$refs.myQuillEditor.quill;
					client().put(fileName, file.file).then(result => {
		        let length = quill.getSelection().index;
		        quill.insertEmbed(length, 'image', result.url);
		        quill.setSelection(length + 1);
		        this.listLoading = false;
					}).catch(function (err) {
			       		
			    });
		    },
			handleCurrentChange(val) {
				this.page = val;
				this.getUsers();
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//获取列表
			getUsers:function (){
				this.listLoading = true;
				let para = {
				    page: this.page,
				    size: this.pageSize,
				};
				var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
				});  
				instance.post('admin/platform/manage/getVipConfigList', this.qs.stringify(para)).then(data => {
					let  res = data.data;
					console.log(data);
					if (res.code !== 0) {
						this.$message({
							message: res.msg,
							type: 'error'
						});
					} else {
						console.log(res)
						this.total = res.total;
						this.users = res.rows;
						this.data = res.data;
						this.listLoading = false;
					}
				}); 
			},
			//获取优惠券
			getCoupon:function (){
				let para = {
					page: 1,
					size: 500,
				};
				var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
				});  
				instance.post('admin/coupon/couponsList/v1_0_0', this.qs.stringify(para)).then(data => {
					let  res = data.data;
					if (res.code !== 0) {
						this.$message({
							message: res.msg,
							type: 'error'
						});
					} else {
						this.couponList = res.rows;
					}
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.editForm.id = row.id;
				this.editForm.vipName = row.vipName;
				this.editForm.vipType = row.vipType;
				this.editForm.byPrice = row.byPrice;
				this.editForm.extendCount = row.extendCount;
				this.editForm.goodsOneLevelExtendScale = row.goodsOneLevelExtendScale;
				this.editForm.goodsTwoLevelExtendScale = row.goodsTwoLevelExtendScale;
				this.editForm.oneLevelExtendAmount = row.oneLevelExtendAmount;
				this.editForm.twoLevelExtendAmount = row.twoLevelExtendAmount;
				this.editForm.sales = row.sales;
				this.editForm.couponId = ''
				if(row.couponId > 0){
				    this.editForm.couponId = row.couponId	
				}
				
		        let para = {
				    vipId: row.id
				};
				var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
				});  
				instance.post('admin/platform/manage/getVipConfigDetail', this.qs.stringify(para)).then(data => {
					let  res = data.data;
					console.log(data);
					if (res.code !== 0) {
						this.$message({
							message: res.msg,
							type: 'error'
						});
					} else {
						console.log(res)
						this.editFormVisible = true;
						
						this.editForm.goodsInfo.name = res.data.goodsInfo.name
						this.editForm.goodsInfo.detail = res.data.goodsInfo.detail
						this.editForm.goodsInfo.picUrl = res.data.goodsInfo.picUrl
						this.urlList = res.data.goodsInfo.gallery
					}
				});
				
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							let para = {
								id:this.editForm.id,
								vipName:this.editForm.vipName,
								byPrice:this.editForm.byPrice,
								extendCount:this.editForm.extendCount,
								goodsOneLevelExtendScale:this.editForm.goodsOneLevelExtendScale,
								goodsTwoLevelExtendScale:this.editForm.goodsTwoLevelExtendScale,
								oneLevelExtendAmount:this.editForm.oneLevelExtendAmount,
								twoLevelExtendAmount:this.editForm.twoLevelExtendAmount,
								sales:this.editForm.sales,
								couponId:this.editForm.couponId,
								goodsInfo:JSON.stringify({
									name:this.editForm.goodsInfo.name,
									detail:this.editForm.goodsInfo.detail,
									gallery:this.urlList,
									picUrl:this.editForm.goodsInfo.picUrl,
								})
							}
							var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
							});  
							instance.post('admin/platform/manage/updateVipConfig', this.qs.stringify(para)).then(data => {
								
								let  res = data.data;
								if (res.code !== 0) {
									this.$message({
										message: res.msg,
										type: 'error'
									});
								} else {
									this.editLoading = false;
									this.$message({
										message: '提交成功',
										type: 'success'
									});
									this.$refs['editForm'].resetFields();
									this.editFormVisible = false;
									this.getUsers();
								}
							});
						});
					}
				});
			},
		},
		mounted() {
			this.getUsers();
			this.getCoupon()
		}
	}

</script>

<style scoped>
    .uploadImg{
  	    display: flex;
  	    flex-direction: row;
  	    flex-wrap: wrap;
    }
    .uploadImgItem{
  	    display: flex;
  	    flex-direction: row;
  	    flex-wrap: wrap;
  	    margin-right: 10px;
  	    margin-bottom: 10px;
     	width: 145px;
  	    height: 145px;
  	    position: relative;
    }
    .uploadImgItemDel{
  	    position: absolute;
  	    top: -5px;
  	    right: -5px;
  	    width: 30px;
  	    height: 30px;
    }
</style>